import { defineStore } from 'pinia';

import { adminLogin } from '@/api/login';
import { AdminLoginPasswordParams, AdminLoginPasswordResult } from '@/api/model/loginModel';
import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';
import Cookies from 'js-cookie';

const InitUserInfo: UserInfo = {
  name: '', // 用户名，用于展示在页面右上角头像处
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const adminInfo: AdminLoginPasswordParams = {
        mobilePhone: `${userInfo.account}`,
        password: `${userInfo.password}`,
      };
      const res: AdminLoginPasswordResult = await adminLogin(adminInfo);
      if (res.code === 0) {
        this.token = res.data.token;
        this.userInfo = {
          name: adminInfo.mobilePhone,
          roles: ['all'],
        };
        Cookies.set('a_c_s', this.token, { expires: 7 });
        console.log(this.userInfo);
      } else {
        throw res.message;
      }
    },
    async getUserInfo() {
      const mockRemoteUserInfo = async (token: string) => {
        if (token === this.token) {
          return {
            name: `${this.userInfo.name}`,
            roles: this.userInfo.roles, // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
          };
        }
        // return {
        //   name: 'td_dev',
        //   roles: ['UserIndex', 'MemberBase', 'login'], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
        // };
      };
      const res = await mockRemoteUserInfo(this.token);
      this.userInfo = res;
    },
    async logout() {
      this.token = '';
      this.userInfo = { ...InitUserInfo };
      Cookies.remove('a_c_s');
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token', 'userInfo'],
  },
});
